import socket
import os

def create_web_server(host='0.0.0.0', port=6789, root_dir='./wwwroot'):
    # 创建 TCP 套接字
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((host, port))
    server_socket.listen(1)
    print(f"Server running on http://{host}:{port}")

    while True:
        # 等待客户端连接
        client_socket, client_address = server_socket.accept()
        print(f"Connection from {client_address}")

        try:
            # 接收 HTTP 请求
            request = client_socket.recv(1024).decode('utf-8')
            if not request:
                client_socket.close()
                continue

            # 解析 HTTP 请求
            request_lines = request.split('\n')
            request_line = request_lines[0]
            method, path, _ = request_line.split()

            # 将 URL 路径映射到文件系统路径
            if path == '/':
                path = '/index.html'  # 默认文件
            file_path = os.path.join(root_dir, path.lstrip('/'))

            # 尝试读取文件并生成响应
            try:
                with open(file_path, 'rb') as file:
                    content = file.read()
                    # 构造成功的 HTTP 响应
                    response = (
                        "HTTP/1.1 200 OK\r\n"
                        "Content-Type: text/html\r\n"
                        f"Content-Length: {len(content)}\r\n"
                        "\r\n"
                    ).encode('utf-8') + content
            except FileNotFoundError:
                # 构造 404 响应
                response_body = "<h1>404 Not Found</h1>".encode('utf-8')
                response = (
                    "HTTP/1.1 404 Not Found\r\n"
                    "Content-Type: text/html\r\n"
                    f"Content-Length: {len(response_body)}\r\n"
                    "\r\n"
                ).encode('utf-8') + response_body

            # 发送响应
            client_socket.send(response)

        except Exception as e:
            print(f"Error handling request: {e}")
        finally:
            # 关闭客户端套接字
            client_socket.close()

if __name__ == "__main__":
    # 设置服务器根目录为当前目录
    create_web_server()